﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace DaoHanFeedToWordPressXML
{
    public partial class Form1 : Form
    {
        Dictionary<string, string> dict;
        private string _template;
        private string _feedItems;
        public Form1()
        {
            InitializeComponent();
        }
        private bool LoadDict(string filename) 
        {
            if (File.Exists(filename)==false)
            {
                MessageBox.Show("No such file: " + filename);
                return false;
            }
            else
            {
                dict = new Dictionary<string, string>();
                string[] allliens = File.ReadAllLines(filename);
                for (int i = 0; i < allliens.Length;i++ )
                {
                    if (allliens[i]!="")
                    {
                      if (allliens[i].Contains("|"))
                      {
                          string[] parts = allliens[i].Split(new char[] { '|' });
                          dict.Add(parts[0], parts[1]);
                      }
                    }
                }

                return true;
            }
        }
        private string LoadFeed(string filename)
        {
            string alldata = File.ReadAllText(filename);
            int firstIndex = alldata.IndexOf("<item>");
            int lastIndex = alldata.LastIndexOf("</item>");
            if (firstIndex==-1 || firstIndex>=lastIndex)
            {

                MessageBox.Show("Wrong format check <item> and </item> in the xml feed");
                return "";
            }

            alldata = alldata.Substring(0,  lastIndex+7);
            alldata = alldata.Substring(firstIndex);
            return alldata;
            
        }
        private string LoadTempLate(string filename)
        {
            return File.ReadAllText(filename);
        }
        private void SaveToXML(string filename)
        {
            string output = string.Format(_template, _feedItems);
            File.WriteAllText(filename, output);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            if (of.ShowDialog()==DialogResult.OK)
            {
                textBoxReplace.Text = of.FileName;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            if (of.ShowDialog() == DialogResult.OK)
            {
                textBoxFeed.Text = of.FileName;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            if (of.ShowDialog() == DialogResult.OK)
            {
                textBoxOutput.Text = of.FileName;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            StatusLabel.Text = "...";
           try
           {
               _template = LoadTempLate("wordpress.2012-01-01.xml");
               _feedItems = LoadFeed(textBoxFeed.Text);

               if (checkBoxReplace.Checked == true)
               {
                   if (LoadDict(textBoxReplace.Text))
                   {
                       foreach (KeyValuePair<String, String> entry in dict)
                       {
                           _feedItems = _feedItems.Replace(entry.Key, entry.Value);
                       }
                   }
               }

               SaveToXML(textBoxOutput.Text);
           }
           catch (System.Exception ex)
           {
               MessageBox.Show(ex.Message);	
           }
           StatusLabel.Text = "Done!";
        }

        private string PostData(string feedurl)
        {
            
         string rv = "";
         WebClient wc = new WebClient();
         rv = DownloadString(new WebClient(), feedurl, Encoding.UTF8);             
            return rv;
    
        }
        public String DownloadString(WebClient webClient, String address, Encoding encoding)
        {
            byte[] buffer = webClient.DownloadData(address);

            byte[] bom = encoding.GetPreamble();

            if ((0 == bom.Length) || (buffer.Length < bom.Length))
            {
                return encoding.GetString(buffer);
            }

            for (int i = 0; i < bom.Length; i++)
            {
                if (buffer[i] != bom[i])
                {
                    return encoding.GetString(buffer);
                }
            }

            return encoding.GetString(buffer, bom.Length, buffer.Length - bom.Length);
        }
        private void button5_Click(object sender, EventArgs e)
        {
            StatusLabel.Text = "Downloading...";
            try
            {
                File.WriteAllText("feed.xml", PostData(textBox1.Text));
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            StatusLabel.Text = "Done!";
        }
    }
}
